package com.sun.showcase.interceptor;

import com.sun.showcase.utils.BackendUserToken;
import com.sun.showcase.utils.JwtTokenUtil;
import com.sun.showcase.utils.LoginContext;
import com.sun.showcase.utils.LoginContextHolder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.net.URLDecoder;

@Component
public class LoginContextInterceptor extends HandlerInterceptorAdapter {
	@Autowired
	private JwtTokenUtil jwtTokenUtil;
	@Value("${jwt.header}")
	private String tokenHeader;
	@Value("${jwt.headName}")
	private String tokenHead;

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
			throws Exception {
		//return super.preHandle(request, response, handler);
		try {
			String authHeader=null;
			boolean tokenInHeader = true;
			if(authHeader==null){
				Cookie[] cks = request.getCookies();
				if( cks != null){
					for(Cookie ck : cks){
						if(tokenHeader.equals(ck.getName()) && ck.getPath()==null){
							authHeader = URLDecoder.decode(ck.getValue(),"utf-8");
							tokenInHeader = false;

							break;
						}
					}
				}
			}
			if(authHeader==null){
				authHeader = request.getHeader(this.tokenHeader);
			}
			if (authHeader != null && authHeader.startsWith(this.tokenHead)) {
				BackendUserToken ut = jwtTokenUtil.getBackTokenInfoFromToken(authHeader);
				//已登路，将当期登录者信息保存到线程上下文中
				LoginContext loginContext = buildLoginContext(ut);
				LoginContextHolder.put(loginContext);
			}
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
	}
	
	@Override
	public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
			throws Exception {
		super.afterCompletion(request, response, handler, ex);
		LoginContextHolder.clear();//本次访问结束，清除信息。
	}

	private LoginContext buildLoginContext(BackendUserToken userInfo){
		LoginContext loginContext = createLoginContext();
		loginContext.setUserId(userInfo.getId());
		loginContext.setUserName(userInfo.getUserName());
		loginContext.setUserNickName(userInfo.getNickName());
		loginContext.setShopId(userInfo.getShopId());
		loginContext.setShopName(userInfo.getShopName());
		return loginContext;
	}
	protected LoginContext createLoginContext(){
		return new LoginContext();
	}
}
